package com.maimang.platform.controller.system;

import com.maimang.platform.base.BaseController;
import com.maimang.platform.base.Result;
import com.maimang.platform.common.config.Global;
import com.maimang.platform.common.entity.SysUser;
import com.maimang.platform.common.utils.JwtUtils;
import com.maimang.platform.common.utils.ShiroUtils;
import com.maimang.platform.common.utils.http.ServletUtils;
import com.maimang.platform.enums.Status;
import com.maimang.platform.lang.StringUtils;
import com.maimang.platform.shiro.realm.UserToken;
import com.maimang.platform.tool.ToolJackson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author Rocky
 * @version 1.0.0
 * @类名 SysLoginController
 * @描述 <br>登录验证</br>
 * @日期 2019-03-18
 * @email jintaozhao@qq.com
 */
@Controller
@Api(value = "登录接口", description = "登录接口登录和刷新token")
public class SysLoginController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(SysLoginController.class);

	@GetMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response) {
		// 如果是Ajax请求，返回Json字符串。
		if (ServletUtils.isAjaxRequest(request)) {
			Result result = Result.FAIL(Status.error.code, "未登录或登录超时。请重新登录");
			return ServletUtils.renderString(response, result.toJson());
		}
		return "login";
		// return "login10";
	}

	@PostMapping("/login")
	@ResponseBody
	@ApiOperation(value = "登录", notes = "jwt登录参数jwt=true,返回token位于header")
	public Result ajaxLogin(@RequestParam(name = "username") String username,
	                        @RequestParam(name = "password") String password,
	                        @RequestParam(defaultValue = "false") Boolean rememberMe,
	                        @RequestParam(defaultValue = "false") Boolean jwt, HttpServletResponse response) throws Exception {
		// 默认UsernamePasswordToken
		// UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);

		UserToken token = new UserToken(username, password, rememberMe, false);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			if (jwt) {
				// jwt登录
				Map<String, Object> jwtUserInfo = ShiroUtils.getJwtUserInfo();
				String jwtUserInfoToken = ShiroUtils.getJwtUserInfoToken();
				response.setHeader("token", jwtUserInfoToken);

				return Result.SUCCESS(Status.success).add("data", jwtUserInfo);
			}
			return success();
		} catch (AuthenticationException e) {
			String msg = "用户或密码错误";
			if (StringUtils.isNotEmpty(e.getMessage())) {
				msg = e.getMessage();
			}
			return error(msg);
		}
	}

	@GetMapping("/unauth")
	public String unauth() {
		return "/error/unauth";
	}

	/**
	 * 刷新jwt token
	 *
	 * @param response
	 * @return
	 */
	@PostMapping("/refreshToken")
	@ResponseBody
	@ApiOperation(value = "刷新token", notes = "header带上参数有效token")
	public Result refreshToken(HttpServletResponse response) {
		String token = ServletUtils.getRequest().getHeader("token");
		SysUser sysUser = ShiroUtils.getSysUserByJwtToken(token);
		if (sysUser != null) {
			try {
				String newToken = JwtUtils.createToken(ToolJackson.toJson(sysUser), Global.getJwtOutTime());
				response.setHeader("token", newToken);
				return success();
			} catch (Exception e) {
				logger.error("刷新jwt token");
				return error("系统错误");
			}
		} else {
			return Result.FAIL(Status.token_invalid);
		}
	}
}
